<?php
/*
 * Handles user login/logout through session management
 * Requires an already started session management!
 */
class LoginManager {
	
	const USER = "LOGIN_USERNAME";
	
	private $webuser;
	private $loggedIn;
	
	// read login state from session and load user data if logged in
	public function __construct() {
		$this->clearUser();
		// load webuser if currently logged in
		if (isset($_SESSION[self::USER])) {
			$this->loadUser();
		}
	}
	
	/*
	 * attempts to login with specified credentials
	 * @returns true if login succeeded, else false
	 */
	public function login($name,$password) {
		// try authentication
		try {
			if (Auth::check($name, $password)) {
				$_SESSION[self::USER] = $name;
				$this->loadUser();
				return true;
			}
		} catch (LogicException $e) {
			// well ... log ? ->x<-
		}
		unset($_SESSION[self::USER]);
		$this->clearUser();
		return false;
	}
	
	/*
	 * logs the current user out by removing the session.
	 * ALL session data is lost
	 * @returns true if session was destroyed successfully
	 */
	public function logout() {
		unset($_SESSION[self::USER]);
		session_unset();
		session_destroy();
		$this->clearUser();
	}
	
	/*
	 * loads the currently logged in user's data and returns a propel model
	 * representing him
	 * @returns the propel webuser model class on success else null
	 */
	public function getWebuser() {
		return $this->webuser;
	}
	
	/*
	 * just checks whether user model is set - prefer if user data is not needed
	 * @returns true if logged in, else false
	 */
	public function isLoggedIn() {
		return $this->loggedIn;
	}
	
	private function loadUser() {
		$this->webuser = WebuserQuery::create()->findOneByUsername($_SESSION[self::USER]);
		$this->loggedIn = true;
	}
	
	private function clearUser() {
		$this->webuser = null;
		$this->loggedIn = false;
	}
}
?>